#include "table_view.h"

table_view::table_view(const QSize &max_size, QWidget *parent)
    : base_autoresize_table()
    , max_size_(max_size)
{
}

void table_view::auto_resize()
{
    horizontalHeader()->setStretchLastSection(false);
    verticalHeader  ()->setStretchLastSection(false);

    resizeRowsToContents();
    resizeColumnsToContents();

    const auto content_with_header_width = min_width_for_content() + verticalHeader()->frameGeometry().width();
    setHorizontalScrollBarPolicy(content_with_header_width > max_size_.width()
                                 ? Qt::ScrollBarAlwaysOn
                                 : Qt::ScrollBarAlwaysOff);

    const auto content_with_header_height = min_height_for_content() + horizontalHeader()->frameGeometry().height();
    setVerticalScrollBarPolicy(content_with_header_height > max_size_.height()
                               ? Qt::ScrollBarAlwaysOn
                               : Qt::ScrollBarAlwaysOff);

    const auto table_width = verticalScrollBar()->isVisible()
            ? frameWidth() + content_with_header_width + 1 + verticalScrollBar()->frameGeometry().width()
            : 2*frameWidth() + content_with_header_width;

    const int scroll_bar_width = 17;

    if (table_width > max_size_.width())
    {
        if (table_width - max_size_.width() < scroll_bar_width)
        {
            setMinimumWidth(table_width);
            horizontalHeader()->setStretchLastSection(true);
        }
        else
        {
            setMinimumWidth(max_size_.width());
        }
    }
    else
    {
        setMinimumWidth(table_width);
        horizontalHeader()->setStretchLastSection(true);
    }

    const auto table_height = horizontalScrollBar()->isVisible()
            ? frameWidth() + content_with_header_height + 1 + horizontalScrollBar()->frameGeometry().height()
            : 2*frameWidth() + content_with_header_height;


    if (table_height > max_size_.height())
    {
        if (table_height - max_size_.height() < scroll_bar_width)
        {
            setMinimumHeight(table_height);
            verticalHeader()->setStretchLastSection(true);
        }
        else
        {
            setMinimumHeight(max_size_.height());
        }
    }
    else
    {
        setMinimumHeight(table_height);
        verticalHeader()->setStretchLastSection(true);
    }

    updateGeometry();

    adjust_parent_size();
}


int table_view::min_width_for_content() const
{
    const auto h_header = horizontalHeader();

    int width = 0;
    for(int i = 0; i < h_header->count(); ++i)
        width += qMax(h_header->sectionSizeHint(i), sizeHintForColumn(i));

    return width;
}

int table_view::min_height_for_content() const
{
    const auto v_header = verticalHeader();

    int height = 0;
    for(int i = 0; i < v_header->count(); ++i)
        height += qMax(v_header->sectionSizeHint(i), sizeHintForRow(i));

    return height;
}











